package cn.tomoya.module.topic.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tomoya.common.BaseController;
import cn.tomoya.common.config.SiteConfig;
import cn.tomoya.common.enums.TopicTypeEnum;
import cn.tomoya.exception.ApiException;
import cn.tomoya.module.collect.service.CollectService;
import cn.tomoya.module.reply.entity.Reply;
import cn.tomoya.module.reply.service.ReplyService;
import cn.tomoya.module.topic.entity.Topic;
import cn.tomoya.module.topic.service.TopicService;
import cn.tomoya.module.user.entity.User;
import cn.tomoya.module.user.service.UserService;

/**
 * Created by tomoya.
 * Copyright (c) 2016, All Rights Reserved.
 * http://tomoya.cn
 */
@Controller

@RequestMapping("/topic")
public class TopicController extends BaseController {

    @Autowired
    private TopicService topicService;
    @Autowired
    private ReplyService replyService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private SiteConfig siteConfig;
    @Autowired
    private UserService userService;

    /**
     * 创建话题
     *
     * @return
     */
    @GetMapping("/create")
    public String create() {
        return render("/topic/create");
    }

    /**
     * 保存话题
     *
     * @param title
     * @param content
     * @param model
     * @return
     */
    @PostMapping("/save")
    public String save(String title, String content, Model model, HttpServletResponse response) {
        String errors;
        Topic oldTopic=null;
        if(!StringUtils.isEmpty(title)){
            oldTopic= topicService.findByTitle(title);
        }

        if (StringUtils.isEmpty(title)) {
            errors = "标题不能为空";
        /*}  else if (!siteConfig.getSections().contains(tab)) {
            errors = "版块不存在";*/
        }else if(oldTopic!=null){
            errors="留言主题已经存在";

        } else {
            User user = getUser();
            Topic topic = new Topic();
//            topic.setTab("1");
            topic.setTitle(title);
            topic.setContent(content);
            topic.setInTime(new Date());
            topic.setUp(0);
            topic.setView(0);
            topic.setUser(user);
            topic.setGood(false);
            topic.setTop(false);
            topicService.save(topic);
            return redirect(response, "/topic/" + topic.getId());
        }
        model.addAttribute("errors", errors);
        return render("/topic/create");
    }


    /**
     * 保存展示留言话题
     *
     * @param title
     * @param content
     * @param model
     * @return
     */
    @PostMapping("/promise/save")
    public String savePromise(String title, String content, Model model, HttpServletResponse response) {
        String errors;
        Topic oldTopic=null;
        if(!StringUtils.isEmpty(title)){
            oldTopic= topicService.findByTitle(title);
        }

        if (StringUtils.isEmpty(title)) {
            errors = "标题不能为空";
        /*}  else if (!siteConfig.getSections().contains(tab)) {
            errors = "版块不存在";*/
        }else if(oldTopic!=null){
            errors="留言主题已经存在";

        } else {
            User user = getUser();
            Topic topic = new Topic();
            topic.setTab("2");
            topic.setTitle(title);
            topic.setContent(content);
            topic.setInTime(new Date());
            topic.setUp(0);
            topic.setView(0);
            topic.setUser(user);
            topic.setGood(false);
            topic.setTop(false);
            topicService.save(topic);
            return redirect(response, "/topic/promise/" + topic.getId());
        }
        model.addAttribute("errors", errors);
        return render("/topic/create");
    }


    /**
     * 保存直播留言话题
     *
     * @param title
     * @param content
     * @param model
     * @return
     */
    @PostMapping("/liveshow/save")
    public String saveLiveshow(String title, String content, Model model, HttpServletResponse response) {
        String errors;
        Topic oldTopic=null;
        if(!StringUtils.isEmpty(title)){
            oldTopic= topicService.findByTitle(title);
        }

        if (StringUtils.isEmpty(title)) {
            errors = "标题不能为空";
        /*}  else if (!siteConfig.getSections().contains(tab)) {
            errors = "版块不存在";*/
        }else if(oldTopic!=null){
            errors="留言主题已经存在";

        } else {
            User user = getUser();
            Topic topic = new Topic();
//            topic.setTab("3");
            topic.setTab(String.valueOf(TopicTypeEnum.LIVESHOW.getTypeValue()));
            topic.setTitle(title);
            topic.setContent(content);
            topic.setInTime(new Date());
            topic.setUp(0);
            topic.setView(0);
            topic.setUser(user);
            topic.setGood(false);
            topic.setTop(false);
            topicService.save(topic);
            return redirect(response, "/topic/liveshow/" + topic.getId());
        }
        model.addAttribute("errors", errors);
        return render("/topic/create");
    }

    /**
     * 保存展示留言话题
     *
     * @param title
     * @param content
     * @param model
     * @return
     */
    @PostMapping("/subject/save")
    public String saveSubject(String title, String content, Model model, HttpServletResponse response) {
        String errors;
        Topic oldTopic=null;
        if(!StringUtils.isEmpty(title)){
            oldTopic= topicService.findByTitle(title);
        }

        if (StringUtils.isEmpty(title)) {
            errors = "标题不能为空";
        /*}  else if (!siteConfig.getSections().contains(tab)) {
            errors = "版块不存在";*/
        }else if(oldTopic!=null){
            errors="留言主题已经存在";

        } else {
            User user = getUser();
            Topic topic = new Topic();
            topic.setTab("4");
            topic.setTitle(title);
            topic.setContent(content);
            topic.setInTime(new Date());
            topic.setUp(0);
            topic.setView(0);
            topic.setUser(user);
            topic.setGood(false);
            topic.setTop(false);
            topicService.save(topic);
            return redirect(response, "/topic/" + topic.getId());
        }
        model.addAttribute("errors", errors);
        return render("/topic/create");
    }


    @ResponseBody
    @GetMapping("/topics/{title}")
    public Map<String,Object> findByTopicId(@PathVariable String  title) throws ApiException
    {
        Map<String, Object> result = new HashMap<String,Object>();
        Topic topic = topicService.findByTitle(title);
        if(null == topic){
            result.put("status",400);
        }else{
            result.put("status",200);
            result.put("data",topic);
        }
        return result;
    }


    /**
     * 编辑话题
     *
     * @param id
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/{id}/edit")
    public String edit(@PathVariable int id, HttpServletResponse response, Model model) {
        Topic topic = topicService.findById(id);
        if (topic == null) {
            renderText(response, "话题不存在");
            return null;
        } else {
            model.addAttribute("topic", topic);
            return render("/topic/edit");
        }
    }

    /**
     * 更新话题
     *
     * @param title
     * @param content
     * @return
     */
    @PostMapping("/{id}/edit")
    public String update(@PathVariable Integer id, String tab, String title, String content, HttpServletResponse response) {
        Topic topic = topicService.findById(id);
        User user = getUser();
        if (topic.getUser().getId() == user.getId()) {
           /* if(!siteConfig.getSections().contains(tab)) throw new IllegalArgumentException("版块不存在");*/
            /*topic.setTab(tab);*/
            topic.setTitle(title);
            topic.setContent(content);
            topicService.save(topic);
            return redirect(response, "/topic/" + topic.getId());
        } else {
            renderText(response, "非法操作");
            return null;
        }
    }

    /**
     * 话题详情
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/{id}")
    public String detail(@PathVariable Integer id, HttpServletResponse response, Model model) {
        if (id != null) {
            Topic topic = topicService.findById(id);
            //浏览量+1
            topic.setView(topic.getView() + 1);
            topicService.save(topic);//更新话题数据
            List<Reply> replies = replyService.findByTopic(topic);


            model.addAttribute("topic", topic);
            model.addAttribute("replies", replies);
            model.addAttribute("user", getUser());
            model.addAttribute("author", topic.getUser());
            model.addAttribute("otherTopics", topicService.findByUser(1, 7, topic.getUser()));
            model.addAttribute("collect", collectService.findByUserAndTopic(getUser(), topic));
            model.addAttribute("collectCount", collectService.countByTopic(topic));
            return render("/topic/detail");
        } else {
            renderText(response, "话题不存在");
            return null;
        }
    }


    /**
     * 展示留言（公约）话题详情
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/promise/{id}")
    public String detailPromise(@PathVariable Integer id, HttpServletResponse response, Model model) {
        if (id != null) {
            Topic topic = topicService.findById(id);
            //浏览量+1
            topic.setView(topic.getView() + 1);
            topicService.save(topic);//更新话题数据

            model.addAttribute("topic", topic);
            model.addAttribute("user", getUser());
            model.addAttribute("author", topic.getUser());
            return render("/topic/promiseDetail");
        } else {
            renderText(response, "话题不存在");
            return null;
        }
    }


    /**
     * 话题详情
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/liveshow/{id}")
    public String detailLiveshow(@PathVariable Integer id, HttpServletResponse response, Model model) {
        if (id != null) {
            Topic topic = topicService.findById(id);
            //浏览量+1
            topic.setView(topic.getView() + 1);
            topicService.save(topic);//更新话题数据
            List<Reply> replies = replyService.findByTopic(topic);


            model.addAttribute("topic", topic);
            model.addAttribute("replies", replies);
            model.addAttribute("user", getUser());
            model.addAttribute("author", topic.getUser());
            return render("/topic/liveshowDetail");
        } else {
            renderText(response, "话题不存在");
            return null;
        }
    }


    /**
     * 删除话题
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}/delete")
    public String delete(@PathVariable Integer id, HttpServletResponse response) {
       List<Reply> replyList= replyService.findByTopicId(id);
        if (replyList.size()==0){
            topicService.deleteById(id);
            return redirect(response, "/");
        }else{
            renderText(response,"留言下有回复不能删除");
            return null;

        }





    }

    /**
     * 加/减精华
     * @param id
     * @param response
     * @return
     */
    @GetMapping("/{id}/good")
    public String good(@PathVariable Integer id, HttpServletResponse response) {
        Topic topic = topicService.findById(id);
        topic.setGood(!topic.isGood());
        topicService.save(topic);
        return redirect(response, "/topic/" + id);
    }

    /**
     * 置/不置顶
     * @param id
     * @param response
     * @return
     */
    @GetMapping("/{id}/top")
    public String top(@PathVariable Integer id, HttpServletResponse response) {
        Topic topic = topicService.findById(id);
        topic.setTop(!topic.isTop());
        topicService.save(topic);
        return redirect(response, "/topic/" + id);
    }

    /**
     * 个人资料
     *
     * @param username
     * @param model
     * @return
     */
    @GetMapping("/list/{username}")
    public String profile(@PathVariable String username, Model model) {
        User currentUser = userService.findByUsername(username);
        if (currentUser != null) {
            model.addAttribute("user", getUser());
            model.addAttribute("currentUser", currentUser);
            model.addAttribute("topicPage", topicService.findByUser(1, 7, currentUser));
            model.addAttribute("pageTitle", currentUser.getUsername() + " 我的留言");
        } else {
            model.addAttribute("pageTitle", "用户未找到");
        }
        return render("/topic/list");
    }

    @GetMapping("/search")
    public String search(String q,Integer p,Model model){
        String escapeHtml = StringEscapeUtils.escapeHtml(q);
        String param = StringEscapeUtils.escapeJavaScript(escapeHtml);
        String s = StringEscapeUtils.unescapeHtml(param);

        Page<Topic> page = topicService.findByTitleLike("%"+s+"%",p==null ?1:p,siteConfig.getPageSize());
        List<Topic> topics= page.getContent();
        List<String> tabList = new ArrayList<String>();
//        tabList.add("2");
//        tabList.add("3");
        tabList.add(String.valueOf(TopicTypeEnum.PROMIST.getTypeValue()));
        tabList.add(String.valueOf(TopicTypeEnum.LIVESHOW.getTypeValue()));
        List<Topic> publishTopicList = topicService.findByTabIn(tabList);
        model.addAttribute("publishTopicList", publishTopicList);
        model.addAttribute("page",page);
        model.addAttribute("topics",topics);
        model.addAttribute("q",param);
        model.addAttribute("user", getUser());
        int pages = page.getTotalPages();
        if(pages ==0){
            model.addAttribute("topics",null);
        }
        return render("/search");


    }


}
